package com.bdqn.zhang.controller;

import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSONObject;
import com.bdqn.zhang.pojo.User;
import com.bdqn.zhang.service.UserService;
import com.bdqn.zhang.util.LayData;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/**
 * <Description> <br>
 *
 * @author tao<br>
 * @version 1.0<br>
 * @taskId: <br>
 * @createDate 2019/09/16 15:38 <br>
 * @see com.bdqn.controller <br>
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    /**
     * 1.请求 如何走到后台
     * 2.参数如何传递
     * @return
     */
    @RequestMapping(value="/login",method = RequestMethod.POST)
    public String login(User user,Model model){
        User u =  userService.login(user.getUsername(),user.getPassword());
        if(u != null){
            model.addAttribute("u",u);
            return "index";
        } else {
            model.addAttribute("msg","账号或密码错误");
            return "error";
        }

    }

    @RequestMapping(value="/touser",method = RequestMethod.GET)
    public String toUserList(Model model, HttpSession session){
        return "user/list";
    }

    @RequestMapping(value="/toadd",method = RequestMethod.GET)
    public String toUserAdd(){
        return "user/add";
    }

    @RequestMapping(value="/list",method = RequestMethod.GET)
    @ResponseBody
    public String getUserList(Model model, HttpSession session, @RequestParam("page") Long from, @RequestParam("limit") Long limit){
        LayData data = userService.getAll(from,limit);
        return JSONObject.toJSONString(data);
    }

    @RequestMapping(value="/addSave",method = RequestMethod.POST)
    public String addSave(User user){
       userService.addSave(user);
        return "redirect:touser";
    }

    @RequestMapping(value="/upload")
    @ResponseBody
    public String upload(@RequestParam("file")MultipartFile file) throws Exception{
        FileUtil.writeBytes(file.getBytes(),"D:/upload/1.png");
        return JSONObject.toJSONString(LayData.data_upload(0L,"上传成功"));
    }
}
